var router = require('express').Router();
var Ep = require('eventproxy');

var checkLogin = require('../middlewares/check.js').checkLogin;
var PostSchema = require('../lib/mongo').Post;
var Post = require('../models/posts');
var User = require('../models/users');
var Comment = require('../models/comments');

//所有用户或特定用户的文章页
//eg: GET /posts?author=xxx
router.get('/', async(req, res, next) => {
    var author = req.query.author;
    var ep=new Ep();
    var posts, authors;

    ep.on('err',err=>{
        req.flash('error',err);
        res.redirect('/notify');
    });

    try {
        posts = await Post.getPosts(author);
        authors = await Promise.all(posts.map(post => User.getUserById(post.author)));
        posts = posts.map((post, i) => {
            post.author = authors[i] ? authors[i] : {};
            return post;
        });
        if(!posts.length || !authors.length)return  ep.emit('err','用户或文章不存在');
        res.render('posts', {posts: posts});
    } catch (err) {
        if(err.message.match(/Cast to ObjectId failed/)){//author ID 错误
            return ep.emit('err','用户或文章不存在');
        }
        return next(err);
    }
});

// GET /posts/crate 发表文章页
router.get('/create', checkLogin, (req, res, next) => {
    res.render('create');
});

// POST /posts 发表文章
router.post('/create', checkLogin, (req, res, next) => {
    var ep = new Ep();
    ep.on('post_error', err => {
        req.flash('error', err);
        res.redirect('back');
    });

    var author = req.session.user._id;
    var title = req.fields.title;
    var content = req.fields.content;

    if (!title.trim().length)return ep.emit('post_error', '请填写标题');
    if (!content.trim().length)return ep.emit('post_error', '请填写内容');

    var post = {
        author: author,
        title: title,
        content: content,
        createTime: new Date()
    };
    Post.create(post).then(post => {
        req.flash('success', '发表成功');
        res.redirect(`/posts/${post._id}`);
    }).catch(next);

});

// GET /posts/:postId 文章详情页
router.get('/:postId', async(req, res, next) => {
    var postId = req.params.postId;
    try {
        var post = await Post.getPostById(postId);
        if (!post)throw new Error('文章不存在');

        var [author, comments] = await Promise.all([User.getUserById(post.author), Comment.getComments(post._id)]);
        if (!author)throw new Error('用户不存在');

        var commentAuthors = await Promise.all(comments.map(comment => User.getUserById(comment.author)));
        comments = comments.map((comment, i) => {
            comment.author = commentAuthors[i];
            return comment;
        });
    } catch (err) {
        req.flash('error',err.message);
        return res.redirect('/posts');
    }

    PostSchema.update({_id:postId}, {$inc: {pv: 1}}).then(() => {
        post.author = author;
        res.render('post', {
            post: post,
            comments: comments
        });
    }).catch(next);

});

// GET /posts/:postId/edit 编辑一篇文章
router.get('/:postId/edit', checkLogin, async(req, res, next) => {
    var postId = req.params.postId;
    try {
        var post = await Post.getPostById(postId);
        var author = await User.getUserById(post.author);
        if (!post || !author)throw new Error('用户或文章不存在');
        if (req.session.user._id.toString() !== post.author.toString())throw new Error('没有权限');
        res.render('edit', {post: post});
    } catch (err) {
        req.flash('error','用户或文章不存在');
        res.redirect('/posts');
    }
});

// POST /posts/:postId 更新一篇文章
router.post('/:postId/edit', checkLogin, (req, res, next) => {
    var ep = new Ep();
    ep.on('update_error', err => {
        req.flash('error', err);
        res.redirect('back');
    });

    var author = req.session.user._id;
    var title = req.fields.title;
    var content = req.fields.content;

    if (!title.trim().length)return ep.emit('update_error', '请填写标题');
    if (!content.trim().length)return ep.emit('update_error', '请填写内容');

    var post = {
        author: author,
        title: title,
        content: content
    };
    var postId = req.params.postId;
    PostSchema.update({_id:postId}, post).then(() => {
        req.flash('success', '编辑成功');
        res.redirect(`/posts/${postId}`);
    }).catch(next);
});

// GET /posts/:postId/remove 删除一篇文章
router.get('/:postId/remove', checkLogin, (req, res, next) => {
    var postId = req.params.postId;
    Promise.all([
        //删除文章
        PostSchema.remove({_id:postId}),
        //删除该文章下的所有评论
        Comment.removeByPostId(postId)
    ]).then(() => {
        req.flash('success', '删除成功');
        res.redirect('/posts');
    }).catch(next);
});

// POST /posts/:postId/comment 创建一条留言
router.post('/:postId/comment', checkLogin, (req, res, next) => {
    var postId = req.params.postId;
    var content = req.fields.content;
    if (!content.trim().length) {
        req.flash('error', '请填写内容');
        return res.redirect('back');
    }
    Promise.all([
        //创建留言
        Comment.create({
            postId: postId,
            author: req.session.user._id,
            content: content,
            createdTime: new Date
        }),
        //更新留言统计数
        PostSchema.update({
                _id:postId
            },
            {
                $inc: {
                    commentsCount: 1
                }
            }
        )
    ]).then(() => {
        req.flash('success', '留言成功');
        res.redirect(`/posts/${postId}`);
    }).catch(next);
});

//GET /posts/:postId/comment/:commentId/remove 删除一条留言
router.get('/:postId/comment/:commentId/remove', checkLogin, (req, res, next) => {
    var postId = req.params.postId;
    var commentId = req.params.commentId;
    var author = req.session.user._id;
    Promise.all([
        //删除留言
        Comment.removeById(commentId, author),
        //更新留言统计数
        PostSchema.update({
            _id: postId
        }, {
            $inc: {
                commentsCount: -1
            }
        })
    ]).then(() => {
        req.flash('success','删除留言成功');
        res.redirect(`/posts/${postId}`);
    }).catch(next);
});

module.exports = router;